package com.abbas.smartCity.ui;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;

import androidx.annotation.Nullable;

import com.abbas.smartCity.App;
import com.abbas.smartCity.R;
import com.abbas.smartCity.base.BaseActivity;
import com.abbas.smartCity.bean.ResponseBean;
import com.abbas.smartCity.bean.UploadBean;
import com.abbas.smartCity.bean.UserInfoBean;
import com.abbas.smartCity.retroft.ICallback;
import com.bumptech.glide.Glide;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Objects;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;

/**
 * 用户信息页面
 */
public class UserInfoActivity extends BaseActivity {

    private ImageView im;
    private EditText nickNameEt;
    private CheckBox sexCb;
    private EditText phoneEt;
    private Button changeBt;
    private UserInfoBean.UserBean copyUserData;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_user_info;
    }

    @Override
    protected String setCustomTitle() {
        return "用户信息";
    }

    @Override
    protected void initView() {
        im = (ImageView) findViewById(R.id.im);
        nickNameEt = (EditText) findViewById(R.id.nick_name_et);
        sexCb = (CheckBox) findViewById(R.id.sex_cb);
        phoneEt = (EditText) findViewById(R.id.phone_et);
        changeBt = (Button) findViewById(R.id.change_bt);
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void initData() {
        //将内存当中的用户信息复制一份使用
        copyUserData = gson.fromJson(gson.toJson(App.getUser()), UserInfoBean.UserBean.class);

        //默认给个初始头像
        im.setImageResource(R.drawable.avatar);
        //加载用户头像
        if (!TextUtils.equals("", copyUserData.getAvatar())) {
            Glide.with(UserInfoActivity.this)
                    .load(App.getBaseUrl() + copyUserData.getAvatar())
                    .error(R.drawable.avatar)
                    .into(im);
        }
        //设置用户昵称
        nickNameEt.setText(copyUserData.getNickName() + "");
        //设置用户性别
        sexCb.setChecked(!TextUtils.equals("0", copyUserData.getSex()));
        //设置用户电话
        phoneEt.setText(copyUserData.getPhonenumber().substring(0, 6) + "****");
    }

    @Override
    protected void initEvent() {
        //点击头像上传图片
        im.setOnClickListener((V) -> {
            //检查存储权限，跳转至图库选择
            startPickOneOfStorageImage();
        });

        //点击修改用户信息
        changeBt.setOnClickListener((v) -> {
            if (uploadPath != null) {
                copyUserData.setAvatar(uploadPath);
            }
            copyUserData.setNickName(nickNameEt.getText().toString());
            copyUserData.setSex(sexCb.isChecked() ? "1" : "0");
            //若用户修改电话之外的数据，需要判断当前显示的电话号码是否是已经隐藏信息了的，若是，则不进行修改
            final String phoneString = phoneEt.getText().toString();
            if (!phoneString.contains("*")) {//老程序员似乎更喜欢用indexOf()??
                copyUserData.setPhonenumber(phoneString);
            }
            final RequestBody requestBody = createRequestBody(copyUserData);
            api.changeUserInfo(requestBody).enqueue(new ICallback<ResponseBean>() {
                @Override
                public void onSuccess(Call<ResponseBean> call, ResponseBean data) {
                    if (data.getCode() == 200) {
                        App.setUser(copyUserData);
                        initData();
                    }
                    showToast(data.getMsg());
                }
            });
        });
    }

    @Override
    protected void onStoragePermissionRequestSuccess() {//选择图片
        super.onStoragePermissionRequestSuccess();
        startPickOneOfStorageImage();
    }

    private String uploadPath = null;//上传图片后返回的服务器地址

    @Override
    protected void onImagePickAndLoadUpResult(UploadBean uploadBean, Bitmap bitmap) {
        super.onImagePickAndLoadUpResult(uploadBean, bitmap);
        //将返回的图片地址保存，并加载选择的图片
        uploadPath = uploadBean.getFileName();
        /**
         * @see https://gitee.com/abbasspace/smart-city-2023-2-8/issues/I6TPL1
         * the bug fixed thanks for 'ID'
         */
        String actImgPath = App.getBaseUrl() +
                "/prod-api" +
                uploadPath;
        copyUserData.setAvatar(actImgPath);
        api.changeUserInfo(createRequestBody(copyUserData)).enqueue(new ICallback<ResponseBean>() {
            @Override
            public void onSuccess(Call<ResponseBean> call, ResponseBean data) {
                Glide.with(UserInfoActivity.this)
                        .load(copyUserData.getAvatar())
                        .into(im);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
//
//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        //优先判空 如果图库没有图片，返回应用时Intent将会为null造成闪退，一定要记得判空！！！
//        if (requestCode == PICK_IMAGE_REQUEST_CODE && resultCode == RESULT_OK && data != null && data.getData() != null){
//            //--------------------固定写法----------------------
//            final Uri uri = data.getData();
//            //String[] _data = {MediaStore.Images.Media.DATA};
//            //查询数据库
//            final Cursor cursor = getContentResolver().query(uri, new String[]{"_data"}, null, null, null);
//            //记得判空，并将指针移动至第一位
//            Objects.requireNonNull(cursor).moveToFirst();
//            //获取图片真实路径
//            final String path = cursor.getString(cursor.getColumnIndex("_data"));
//            //解析图片，即图片
//            final Bitmap storageImage = BitmapFactory.decodeFile(path);
//            //关闭流
//            Objects.requireNonNull(cursor).close();
//            //--------------------结束-------------------------
//
//            //上传图片
//            //构造图片文件
//            final File uploadImageFile = new File(path);
//            //设置请求体数据格式，并将图片放入请求体
//            final RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), uploadImageFile);
//            //新建一个Part对象，将上传的文件传入并指定文件名
//            final MultipartBody.Part multipartBody = MultipartBody.Part.createFormData("file", uploadImageFile.getName(), requestBody);
//            api.postFile(
//                    multipartBody
//            ).enqueue(new ICallback<UploadBean>() {
//                @Override
//                public void onSuccess(Call<UploadBean> call, UploadBean data) {
//                    //上传回调
//                    if (data.getCode() == 200) {
//                        //上传成功
//                        final String uploadImagePath = data.getUrl();//上传的图片路径，但后端返回了一个错误的路径，此路径无法加载
//                        //加载图片
//                        Glide.with(this)
//                                .load(App.getBaseUrl() + uploadImagePath)
//                                .into(imageView);
//                    }
//                }
//            });
//
//            //直接从本地获取图片
//            try {
//                final Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
//                bitmap.recycle();
//            } catch (FileNotFoundException e) {
//                e.printStackTrace();
//            }
//
//        }
//    }

}